package me.leiusual.sharing.ui.shop

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import dagger.android.support.DaggerFragment
import kotlinx.android.synthetic.main.fragment_shop_bank_edit.*
import me.leiusual.sharing.R
import me.leiusual.sharing.api.model.Bank
import me.leiusual.sharing.repository.model.Data
import me.leiusual.sharing.ui.helper.HandleObserver
import me.leiusual.sharing.util.extension.toast
import timber.log.Timber
import javax.inject.Inject

/**
 * author: leiusual
 * create on: 2019-07-29
 * description:
 */
class ShopBankEditFragment : DaggerFragment(), View.OnClickListener {

  @Inject
  lateinit var factory: ViewModelProvider.Factory

  private val viewModel: ShopBankEditViewModel by viewModels { factory }

  private val args: ShopBankEditFragmentArgs by navArgs()

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_shop_bank_edit, container, false)
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    toolbar.setNavigationOnClickListener {
      findNavController().popBackStack()
    }

    text_view_account_type.setOnClickListener(this)

    button_update.setOnClickListener(this)

    tryFillData()

    observeData()
  }

  override fun onClick(v: View?) {
    when (v?.id) {
      R.id.text_view_account_type -> {
        viewModel.accountType()
      }
      R.id.button_update -> {
        doBankUpdate()
      }
    }
  }

  private fun tryFillData() {
    val bank = args.bank
    if (bank == null) {
      text_view_title.text = "编辑银行账号"
      button_update.text = "保存"

    } else {
      text_view_title.text = "更新银行账号"
      button_update.text = "更新"

      // 类型
      viewModel.accountTypeSelected(mapOf(bank.accountType to bank.accountTypeName))

      edit_text_bank_card_id.setText(bank.bankCardId)
      edit_text_card_owner_name.setText(bank.cardOwnerName)
      edit_text_bank_name.setText(bank.bankName)
      switch_default.isChecked = bank.defaultAccount
      switch_default.isEnabled = !bank.defaultAccount
    }
  }

  private fun observeData() {
    viewModel.accountType.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("accountType = %s", it)
      when (it) {
        is Data.Loading -> {

        }
        is Data.Error -> {

        }
        is Data.Success -> {
          dialogAccountType(it.data)
        }
      }
    })

    viewModel.accountTypeSelected.observe(viewLifecycleOwner, Observer {
      Timber.v("accountTypeSelected = %s", it)

      text_view_account_type.text = it.values.firstOrNull()
    })

    viewModel.bankUpdate.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("bankUpdate = %s", it)
      when (it) {
        is Data.Loading -> {
          button_update.isEnabled = false
        }
        is Data.Error -> {
          button_update.isEnabled = true
          toast(it.error.message)
        }
        is Data.Success -> {
          button_update.isEnabled = true
          findNavController().popBackStack()
        }
      }
    })
  }

  private fun dialogAccountType(map: Map<String, String>) {
    val values = map.values.toTypedArray()
    AlertDialog.Builder(requireContext())
        .setItems(values) { _, witch ->
          viewModel.accountTypeSelected(map.filterValues { it == values[witch] })
        }
        .show()
  }

  private fun doBankUpdate() {
    val accountType = viewModel.accountTypeSelected.value
    if (accountType == null || accountType.isEmpty()) {
      toast("请选择账户类型")
      return
    }

    val bankCardId = edit_text_bank_card_id.text.toString()
    val cardOwnerName = edit_text_card_owner_name.text.toString()
    val bankName = edit_text_bank_name.text.toString()
    val default = switch_default.isChecked

    val bank = Bank(
        args.bank?.id ?: 0,
        accountType.keys.first(),
        accountType.values.first(),
        bankCardId,
        bankName,
        cardOwnerName,
        default
    )
    viewModel.bankUpdate(bank)
  }
}